package cn.wzb.hrm.service.impl;

import cn.wzb.hrm.domain.Sso;
import cn.wzb.hrm.domain.VipBase;
import cn.wzb.hrm.dto.RegistryDto;
import cn.wzb.hrm.feignclient.RedisFeignClient;
import cn.wzb.hrm.mapper.SsoMapper;
import cn.wzb.hrm.mapper.VipBaseMapper;
import cn.wzb.hrm.service.ISsoService;
import cn.wzb.hrm.util.AjaxResult;
import cn.wzb.hrm.util.encrypt.MD5;
import cn.wzb.hrm.vo.SMSCodeVo;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.UUID;

/**
 * <p>
 * 会员登录账号 服务实现类
 * </p>
 *
 * @author wzb
 * @since 2020-04-29
 */
@Service
public class SsoServiceImpl extends ServiceImpl<SsoMapper, Sso> implements ISsoService {

    @Autowired
    private RedisFeignClient redisFeignClient;

    @Autowired
    private VipBaseMapper vipBaseMapper;

    @Override
    public void register(RegistryDto registryDto) {

        //1.判断基本参数
        String mobile = registryDto.getMobile();
        String password = registryDto.getPassword();
        String smsCode = registryDto.getSmsCode();

        //2.判断手机号已经被注册
        Sso ssoInMysql = baseMapper.selectByPhone(mobile);
        if(ssoInMysql != null){
            throw new RuntimeException("手机号已经被注册");
        }

        //3.判断手机验证码是否正确：
        String SMSCodeKeyInRedis = "sms:"+mobile;

        //3.1.根据 sms:手机号  作为key从Redis中获取验证码发送记录
        AjaxResult lastSMSCodeResult = redisFeignClient.getString(SMSCodeKeyInRedis);
        if(!lastSMSCodeResult.isSuccess() || lastSMSCodeResult.getResultObj() == null){
            throw new RuntimeException("手机验证码获取失败，请重新发送");
        }
        //3.2.判断redis中的验证码和传入的验证码是否一致
        SMSCodeVo smsCodeVo = JSON.parseObject(lastSMSCodeResult.getResultObj().toString(), SMSCodeVo.class);
        if(!smsCodeVo.getCode().equals(smsCode.trim())){
            throw new RuntimeException("手机验证码错误，请重新发送");
        }

        long time = new Date().getTime();
        //4.保存用户信息：t_sso
        Sso sso = new Sso();
        sso.setPhone(mobile);
        sso.setCreateTime(time);
        //加密：加盐
        //创建一个盐
        String salt = MD5.getRandomCode(16);
        sso.setSalt(salt);
        String md5Password = MD5.getMD5(password + salt);
        sso.setPassword(md5Password);

        baseMapper.insert(sso);
        //5.初始化t_vip_base表
        VipBase vipBase = new VipBase();
        vipBase.setCreateTime(time);
        vipBase.setSsoId(sso.getId());
        vipBase.setRegChannel(0); //0网站注册 ，1手机注册
        vipBase.setRegTime(time);
        vipBaseMapper.insert(vipBase);

    }

    @Override
    public String login(Sso sso) {
        //1.判断基本参数
        if(!StringUtils.hasLength(sso.getPhone()) || !StringUtils.hasLength(sso.getPassword())){
            throw new RuntimeException("无效的用户名或密码");
        }

        //2.根据用户名查询SSO
        Sso ssoFromMysql = baseMapper.selectByPhone(sso.getPhone());
        if(ssoFromMysql == null ){
            throw new RuntimeException("无效的用户名码");
        }

        //3.对比密码
        //数据库的密码,暗文
        String password = ssoFromMysql.getPassword();
        //前台传过来的明码,需要加盐与转换为暗文
        String md5 = MD5.getMD5(sso.getPassword() + ssoFromMysql.getSalt());

        if(!password.equals(md5)){
            throw new RuntimeException("无效的密码");
        }

        //4.把登录信息放到redis
        //Redis的key
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        ssoFromMysql.setPassword("");
        AjaxResult result = redisFeignClient.setex(token, 60 * 60, JSON.toJSONString(ssoFromMysql));
        if(!result.isSuccess()){
            throw new RuntimeException("登录失败,请联系管理员");
        }

        //5.把redis的key返回
        return token;
    }
}
